package org.yelongframework.model.support.mybatis.sql.fragment.condition;

import java.util.Set;

import org.apache.commons.lang3.ArrayUtils;
import org.yelongframework.model.support.mybatis.sql.MybatisBoundSql;
import org.yelongframework.model.support.mybatis.sql.MybatisParamMap;
import org.yelongframework.model.support.mybatis.sql.fragment.MybatisSqlFragmentException;
import org.yelongframework.sql.bound.SqlBound;
import org.yelongframework.sql.fragment.condition.simple.DefaultSimpleConditionSqlFragment;

/**
 * mybatis简单条件SQL片段
 * 
 * @since 1.0.0
 */
public class DefaultMybatisSimpleConditionSqlFragment extends DefaultSimpleConditionSqlFragment
		implements MybatisSimpleConditionSqlFragment {

	public DefaultMybatisSimpleConditionSqlFragment(String conditionFragment, Object[] params) {
		super(conditionFragment, params);
	}

	@Override
	public MybatisBoundSql getMybatisBoundSql() {
		MybatisParamMap mybatisParamMap = new MybatisParamMap("MYBATISPARAM");
		SqlBound boundSql = getSqlBound(null);
		String sql = boundSql.getSql();
		Object[] params = boundSql.getParams();
		String mybatisSql = "";
		if (!ArrayUtils.isEmpty(boundSql.getParams())) {
			for (Object obj : params) {
				mybatisParamMap.addParamMap(obj);
			}
			StringBuilder conditionSqlFragment = new StringBuilder(sql);
			Set<String> mybatisParamPlaceholderSet = mybatisParamMap.getPlaceholderParamMap().keySet();
			for (String paramPlaceholder : mybatisParamPlaceholderSet) {
				int index = conditionSqlFragment.indexOf("?");
				conditionSqlFragment.replace(index, index + 1, paramPlaceholder);
			}
			mybatisSql = conditionSqlFragment.toString();
		} else {
			mybatisSql = sql;
		}
		return new MybatisBoundSql(mybatisSql, mybatisParamMap);
	}

	@Override
	public void setParamAlias(String paramAlias) {
		throw new MybatisSqlFragmentException("暂未实现！");
	}

	@Override
	public String getParamAlias() {
		throw new MybatisSqlFragmentException("暂未实现！");
	}

}
